package com.perfma.xtest.http;

import ch.qos.logback.classic.Level;
import org.asynchttpclient.*;

import java.util.concurrent.ConcurrentLinkedQueue;

/**
 *
 *
 * @author: junhui.si
 * @date: 2024-05-14 13:57
 **/
public class Http1 {

    public static ConcurrentLinkedQueue<Domain> queue = new ConcurrentLinkedQueue<>();

    public static void main(String[] args) throws InterruptedException {
        ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
        root.setLevel(Level.INFO);

        Thread.sleep(3000);

        new Thread(() -> {
            AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient(new DefaultAsyncHttpClientConfig.Builder()
                    .setConnectTimeout(60000)
                    .setRequestTimeout(60000)
                    .build());
            int size = 5000;
            for (int i = 0; i < size; i++) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                RequestBuilder requestBuilder = new RequestBuilder();
                // 添加URL
                requestBuilder.setUrl("https://img.alicdn.com/tps/TB1PlWbKFXXXXbmXFXXXXXXXXXX-16-16.ico");
                ListenableFuture<Response> listenableFuture = asyncHttpClient
                        .executeRequest(requestBuilder);
                Domain domain = Domain.builder()
                        .requestBuilder(requestBuilder)
                        .listenableFuture(listenableFuture)
                        .startTime(System.currentTimeMillis())
                        .build();
                queue.offer(domain);
            }
        }).start();

        long startTime = System.currentTimeMillis();
        waitAllDone();
        System.out.println("总耗时：" + (System.currentTimeMillis() - startTime));
    }

    public static void waitAllDone() {
        // 方式 1
        int i = 1;
        while (true) {
            Domain domain = queue.poll();
            if (domain == null) {
                continue;
            }
            ListenableFuture<Response> listenableFuture = domain.getListenableFuture();
            if (listenableFuture.isDone()) {
                try {
                    Response result = listenableFuture.get();
                    System.out.println("耗时" + (i++) + "：" + (System.currentTimeMillis() - domain.getStartTime()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                queue.add(domain);
            }
        }

//        Iterator<ListenableFuture<Response>> it = responses.iterator();
//        try {
//            while (it.hasNext()) {
//                ListenableFuture<Response> response = it.next();
//                try {
//                    if (response.isDone()) {
//                        System.out.println("-------");
//                        Response result = response.get();
//                    }
//                } catch (ExecutionException e) {
//                    e.printStackTrace();
//                }
//            }
//
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
    }

//    /**
//     * 执行异步HTTP请求
//     */
//    public void asyncRequest() {
//        String url = "http://www.baidu.com";
//        AsyncHttpClient c = new DefaultAsyncHttpClient();
//        Future<Response> f = c.prepareGet(url).execute(new AsyncCompletionHandler<Response>() {
//
//            // onCompleted method will be invoked once the http response has been fully read.
//            //一旦完全读取Http响应，就调用onCompleted方法
//            //Response object includes the http headers and the response body.
//            //Response 对象包括HTTP请求头和响应体
//            @Override
//            public Response onCompleted(Response response) throws Exception {
//                System.out.println("完成请求");
//                return response;
//            }
//
//            @Override
//            public void onThrowable(Throwable t) {
//                System.out.println("出现异常");
//                super.onThrowable(t);
//            }
//        });
//
//        try {
//            Response response = f.get();
//            System.out.println(response.getResponseBody());
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        } catch (ExecutionException e) {
//            e.printStackTrace();
//        }
//
//    }

}
